﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Data;

namespace KgUtils.EntityFramework
{
    public static partial class EntityObjectExtension
    {
        public static T[] GetSingleIdFromEntityKey<T>(this EntityObject entity)
        {
            var key = entity.EntityKey;

            if (key != null)
                return key.EntityKeyValues.Select(eKey => (T)eKey.Value).ToArray();
            else
                return new T[] {};
        }

        public static string GetEntityPrimaryKeyName(this EntityObject entity)
        {
            var entityType = entity.GetType();
            foreach (var propInfo in entityType.GetProperties())
            {
                var edmScale = (EdmScalarPropertyAttribute)propInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true).FirstOrDefault();
                if (edmScale != null)
                {
                    if (edmScale.EntityKeyProperty)
                    {
                        //Primary key
                        return propInfo.Name;
                    }
                }
            }
            return null;
        }

        public static List<string> GetEntityPrimaryKeyNames(this EntityObject entity)
        {
            var results = new List<string>();
            var entityType = entity.GetType();
            foreach (var propInfo in entityType.GetProperties())
            {
                var edmScale = (EdmScalarPropertyAttribute)propInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true).FirstOrDefault();
                if (edmScale != null)
                {
                    if (edmScale.EntityKeyProperty)
                    {
                        //Primary key
                        results.Add(propInfo.Name);
                    }
                }
            }
            return results;
        }
    }
}
